package com.llap.exp190929.controller;

import com.llap.exp190929.dto.PaginatedDto;
import com.llap.exp190929.entity.Sale;
import com.llap.exp190929.entity.User;
import com.llap.exp190929.error.RestException;
import com.llap.exp190929.error.UnauthorizedException;
import com.llap.exp190929.service.SaleService;
import com.llap.exp190929.util.Util;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;

/**
 * Created by LLAP on 2019/10/14.
 * Copyright (c) 2019 LLAP. All rights reserved.
 */
@RestController
@RequestMapping("sales")
@AllArgsConstructor
@CrossOrigin
@Slf4j
public class SalesController {
    private SaleService saleService;

    @GetMapping("")
    public PaginatedDto<Sale> findSales(
            @RequestParam(required = false, defaultValue = "1") Integer page,
            @RequestParam(required = false, defaultValue = "20") Integer pageSize,
            @RequestParam(required = false, defaultValue = "salesDate") String sortBy) {
        return PaginatedDto.from(saleService.findSales(page, pageSize, sortBy));
    }

    @GetMapping("{id}")
    public Sale findSale(@PathVariable Integer id) {
        return saleService.findSale(id);
    }

    @PostMapping("")
    public Sale addSale(@RequestBody Sale sale) throws RestException {
        User user = User.from(Util.getLoginUser());
        if (user == null) throw new UnauthorizedException("");
        sale.setSalesDate(new Date());
        sale.setUser(user);
        sale.setTotalPrice(sale.getPrice().multiply(BigDecimal.valueOf(sale.getQuantity())));
        return saleService.addSale(sale);
    }

}
